import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mvvm_provider/page/collection/widget/collection_item.dart';
import 'package:mvvm_provider/page/collection/widget/show_novels_widget.dart';
import 'package:mvvm_provider/page/home/data/model/cartoon_model.dart';
import 'package:mvvm_provider/until/app_util.dart';
import 'package:provider/provider.dart';
import '../../../base/base_stateful_page.dart';
import '../view_model/collection_view_model.dart';
import '../view_model/handle_data_view_model.dart';

class CollectionPage extends BasePage {
  const CollectionPage({super.key});

  @override
  BasePageState<BasePage> getState() => _CollectionPageState();
}

class _CollectionPageState extends BasePageState<CollectionPage> {
  @override
  void initState() {
    super.initState();
    super.pageTitle = '收藏';
  }

  @override
  Widget right() {
    return Align(
      alignment: Alignment.center,
      child: InkWell(
        onTap: _showBottomSheet,
        child: const Text(
          '添加',
          style: TextStyle(color: Colors.blue),
        ),
      ),
    );
  }

  /// 展示弹窗
  Future<void> _showBottomSheet() async {
    final collectionViewModel = context.read<CollectionViewModel>();
    final handleDataViewModel = context.read<HandleDataViewModel>();
    EasyLoading.show();
    List<CartoonModel>? list = await collectionViewModel.getAllListData();
    List<CartoonModel>? collectionList = collectionViewModel.getCollectionListData();
    EasyLoading.dismiss();
    if (AppUtil.isEmpty(list)) return;
    if (context.mounted) {
      CartoonModel? model = await showNovelWidget(context, list!, collectionList ?? []);
      if (model == null) return;
      if (model.isCollection ?? false) {
        handleDataViewModel.cancelCollectionNovel(model.itemId ?? "");
      } else {
        handleDataViewModel.collectionNovel(model);
      }
    }
  }

  @override
  Widget buildPage(BuildContext context) {
    return Consumer<CollectionViewModel>(
        builder: (BuildContext context, CollectionViewModel value, Widget? child) {
      List<CartoonModel>? list = value.getCollectionListData();
      if (AppUtil.isEmpty(list)) return const Center(child: Text('暂无数据'));
      return ListView.builder(
        itemCount: list!.length,
        scrollDirection: Axis.vertical,
        itemBuilder: (BuildContext context, int index) {
          return CollectionItem(model: list[index]);
        },
      );
    });
  }
}
